import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@Component({
	selector: 'sa-complaint-record-page',
    templateUrl: './complaint-record-page.component.html',
    styleUrls:['./complaint-record-page.component.css'],
})
export class ComplaintRecordPageComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
            },
            parentCompanyName: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择所属厂区'
					}
				}
			},
            complainPhenomenon: {
				validators: {
					notEmpty: {
						message: '请选择投诉现象'
					}
				}
			},
			// complainTime:{
			// 	trigger:"change",
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请选择投诉时间'
			// 		},
			// 		date: {
            //             format: 'YYYY-MM-DD h:m:s',
            //             message: '请输入正确的时间,例如2018-01-00 00:00:00'
            //         }
			// 	}
            // },
            reasons: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择后台判断原因'
					}
				}
			},
			// fixTime:{
			// 	trigger:"change",
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请选择维修时间'
			// 		},
			// 		date: {
            //             format: 'YYYY-MM-DD h:m:s',
            //             message: '请输入正确的时间,例如2018-01-00 00:00:00'
            //         }
			// 	}
			// }
			callCount: {
                validators: {
                    callback:{
                        callback:function(value,validator,$field){
                            if(value){
								var reg = /^\+?[1-9][0-9]*$/;
								if(!reg.test(value)){
									return{
										valid:false,
										message:'必须是正整数'
									}
								}else{
									return true;
								}
                            }else{
                                return true;
                            }
                        }
                    },
                }
			},
			callDuration: {
                validators: {
                    callback:{
                        callback:function(value,validator,$field){
                            if(value){
								var reg = /^\+?[1-9][0-9]*$/;
								if(!reg.test(value)){
									return{
										valid:false,
										message:'必须是正整数'
									}
								}else{
									return true;
								}
                            }else{
                                return true;
                            }
                        }
                    },
                }
            },
		}
	};
	page: any = {
		deviceId:'',
		carNumber: '',
		complainTime:'',
        fixTime:'',
        companyName:'',
        companyId:'',
        complainPhenomenon: '',
        reasons: '',
        isNotice: '0',
        isFix: '0',
        remark: '',
        projectId: '',
		complainPath: '',
		conversationPath: '',
		noRepairedReason: '',
		appointRepairedTime: '',
		callUser: '',
		callDuration: '',
		callTime: '',
		callCount: '',
		isSynchronizationRepaired: 0
    };
    isShared: boolean = true;
    repair: boolean = true;
    projectList: any
	page_title:string = '新增';
	pageType:string = 'new';
	recordId = '';
	curPage = 0;
    imageInfo : any={
        "localImg":[],
        "imageList":[],
        "describe": '投诉截图'
    }
    imageCar: any = {
        "localImg":[],
        "imageList":[],
        "describe": '与司机通话截图'
    }
    isViewer:boolean = false; //默认隐藏
    //显示图片组件
    viewer: any='';
    fileList: File = null;
	bigImg:any='' //
	orderId: any ='' //从订单监控页面携带过来
	isCar: any = false // 默认车牌号码可以更改
	hour:any = '' //时
	minute:any = '' //分
	second:any = '' //秒
	tian:any = '' //天
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.recordId = queryParams.id;
			this.pageType = queryParams.type;
			this.curPage = queryParams.nowPage;
			this.orderId = queryParams.orderId;
			if(queryParams.type == 'new'){
				this.page_title = '新增';
				if(queryParams.orderId){
					//判断车牌号码可不可以更改
					this.isCar = true;
					this.page.deviceId = queryParams.deviceId;
					this.page.carNumber = queryParams.carNumber;
					this.page.companyId = queryParams.companyId;
					this.page.companyName = queryParams.companyName;
					var date = new Date();
					$("#complainTime").val(common.getTimeMmss(date));//当前时间
					this.page.complainTime = common.getTimeMmss(date);
					$("#carNumberInput").val(queryParams.carNumber).change();
					console.log(queryParams.carNumber)
				}
			}else{
				this.page_title = '编辑';
			}
		});
	}
	onSubmit(){
		if(this.page.callDuration){
			if(this.page.callCount == '' || this.page.callCount == null){
				this.jsonApiService.message("通话时长有数据时，拨打次数不能为空");
				return;
			}
			if(this.page.callUser == ''){
				this.jsonApiService.message("通话时长有数据时，拨打人不能为空");
				return;
			}
		}

		if(this.page.callCount){
			if(this.page.callDuration == '' || this.page.callDuration == null){
				this.jsonApiService.message("拨打次数有数据时，通话时长不能为空");
				return;
			}
			if(this.page.callUser == ''){
				this.jsonApiService.message("拨打次数有数据时，拨打人不能为空");
				return;
			}
		}

		if(this.page.callUser){
			if(this.page.callDuration == '' || this.page.callDuration == null){
				this.jsonApiService.message("拨打人有数据时，通话时长不能为空");
				return;
			}
			if(this.page.callCount == '' || this.page.callCount == null){
				this.jsonApiService.message("拨打人有数据时，拨打次数不能为空");
				return;
			}
		}

		//当选中是维修的时候，维修时间必填
		if(this.page.isFix== '1'){
			if($('#fixTime').val() == ''){
				this.jsonApiService.message("确定维修时，维修时间不能为空");
				$('.btn').attr("disabled",false);
				return;
			}
		}
		
		$('#recordForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#recordForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			this.updata();
		}
	}
	updata(){
		this.page.complainTime = $('#complainTime').val();
		this.page.fixTime = $('#fixTime').val();
		this.page.appointRepairedTime = $('#appointRepairedTime').val();
		this.page.callTime = $('#callTime').val();


		if(this.imageCar.imageList.length != 0 || this.page.callDuration > 0){
			this.isShared = false;
			this.page.isNotice = "1";
		}

		var	submitObj;
		var	submitObj1 = {
			deviceId:this.page.deviceId,
			carNumber: this.page.carNumber,
			complainTime:this.page.complainTime,
			fixTime:this.page.fixTime,
			companyName:this.page.companyName,
			companyId:this.page.companyId,
			complainPhenomenon: this.page.complainPhenomenon,
			complainPath: this.imageInfo.imageList.join(","),
			conversationPath: this.imageCar.imageList.join(","),
			reasons: this.page.reasons,
			isNotice: this.page.isNotice,
			isFix: this.page.isFix,
			remark: this.page.remark,
			noRepairedReason: this.page.noRepairedReason,
			appointRepairedTime: this.page.appointRepairedTime,
			callUser: this.page.callUser,
			callDuration: this.page.callDuration,
			callTime: this.page.callTime,
			callCount: this.page.callCount,
			isSynchronizationRepaired: this.page.isSynchronizationRepaired
		}

		if(this.page.callDuration < 1){
			delete submitObj1['callDuration']
		}
		if(this.page.callCount < 1){
			delete submitObj1['callCount']
		}

		if(this.pageType != 'new'){
			var submitObj2 = {
				id:this.recordId,
			}
			submitObj = Object.assign(submitObj1, submitObj2);
		}else{
			submitObj = submitObj1
		}
		const fm = new FormData();
		for(var item in submitObj){
			// if(submitObj[item]){
				fm.append(item,submitObj[item]);
			// }
		}
		
		this.jsonApiService.form_http('projectOperations/editOrInsertComplain.html',fm).subscribe(data=> {
			// this.jsonApiService.message(data.message);
			if(data.success){
				if(this.pageType != 'new'){
					this.jsonApiService.message("编辑成功");
				}else{
					this.jsonApiService.message("添加成功");
				}

				if(this.orderId){
					console.log("该订单是从订单监控来的");
					let reqdata='orderId='+this.orderId;
					this.jsonApiService.http("orderController/complaintRecord.html", reqdata).subscribe(result => {
						if(result.success){
							console.log("订单监控提交成功")
						}
					})
				}

				this.router.navigate(['/wx-bind/complaint-record'],{ queryParams: {nowPage:this.curPage}});
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	//	返回资源列表页
	goBack() {
		this.router.navigate(['/wx-bind/complaint-record'],{ queryParams: {nowPage:this.curPage}});
	}
	//初始化车辆
	initCar(){
		var that = this;
		$("#carNumberSelect2").select2({
            language : "zh-CN",
            minimumInputLength: 2,
			allowClear: true,
			placeholder:"请选择",
			ajax: {
	    		url: config.BaseURL+"stats/carListByCarNumber.html",
	    		dataType: 'json',
	    		delay: 50,
	    		method: "POST",
	    		xhrFields: {withCredentials: true},
	    		data: function (params){return {"carNumber" :  params.term};},
	    		processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]",
									companyId: car.companyId,
									parentName: car.parentName
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber,
									companyId: car.companyId,
									parentName: car.parentName
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber,
								companyId: car.companyId,
								parentName: car.parentName
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
	    		cache: true
	        },
            templateResult : function (state){
            	if (!state.id) {return state.text;}
                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                return $state;
            },
       }).on("select2:select", function (e){
			console.log(e)
        	var data = e.params.data;
			that.page.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.page.carNumber = data.text.split('[')[0];
			} else {
				that.page.carNumber = data.text;
			}
			// that.page.carNumber = data.text;
			that.page.companyId = data.companyId;
			that.page.companyName = data.parentName;
        	$("#carNumberInput").val(that.page.carNumber).change();
        });
	
	}
	//初始化日期
	initDate(){
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
				$("#complainTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#complainTime").datetimepicker("setStartDate", time);
				});
				$("#fixTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#fixTime").datetimepicker("setStartDate", time);
				});
				$("#callTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#callTime").datetimepicker("setStartDate", time);
				});
				$("#appointRepairedTime").datetimepicker({//时间插件
					format: "yyyy-mm-dd hh:ii:ss",
				    language: "zh-CN",
				    autoclose: true,
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeMmss(date);
					$("#appointRepairedTime").datetimepicker("setStartDate", time);
				});
			});
		});
	}
	ngOnInit(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.initCar();
				this.getEditMessage();
			})
		});
		this.initDate();
	}
	getEditMessage(){
		if(this.recordId){
			let reqdata='id='+this.recordId;
			this.jsonApiService.http("projectOperations/complainInfo.html", reqdata).subscribe(result => {
				if(result.success){

					if(result.data.conversationPath || result.data.callDuration > 0){
						this.isShared = false;
						this.page.isNotice = "1";
					}

					this.page.deviceId  = result.data.deviceId;
					this.page.carNumber = result.data.carNumber;
					this.page.complainTime = result.data.complainTime;
					this.page.fixTime = result.data.fixTime;
					this.page.companyName = result.data.companyName;
					this.page.companyId = result.data.companyId;
					this.page.complainPhenomenon = result.data.complainPhenomenon;
					this.page.reasons = result.data.reasons;
					this.page.isNotice = result.data.isNotice;
					this.page.isFix = result.data.isFix;
					this.page.remark  = result.data.remark;
					this.page.noRepairedReason  = result.data.noRepairedReason,
					this.page.appointRepairedTime  = result.data.appointRepairedTime,
					this.page.callUser  = result.data.callUser,
					this.page.callDuration  = result.data.callDuration,
					this.page.callTime  = result.data.callTime,
					this.page.callCount  = result.data.callCount,
					this.page.isSynchronizationRepaired = result.data.isSynchronizationRepaired


					if(result.data.callCount == 0){
						this.page.callCount = ''
					}
					if(result.data.callDuration == 0){
						this.page.callDuration = ''
					}

					// if(result.data.callDuration){
						
					// 	var callTime = common.secondToDate(result.data.callDuration);

					// 	if(callTime.indexOf("天") != -1){
					// 		this.tian = callTime.match(/(\S*)天/)[1];
					// 	}else if(callTime.indexOf("时") != -1 && callTime.indexOf("天") != -1){
					// 		this.hour = callTime.match(/天(\S*)时/)[1];
					// 	}else if(callTime.indexOf("时") != -1 && callTime.indexOf("天") == -1){
					// 		this.minute = callTime.match(/(\S*)时/)[1];
					// 	}else if(callTime.indexOf("分") != -1 && callTime.indexOf("时") != -1){
					// 		this.hour = callTime.match(/时(\S*)分/)[1];
					// 	}else if(callTime.indexOf("分") != -1 && callTime.indexOf("时") == -1){
					// 		this.minute = callTime.match(/(\S*)分/)[1];
					// 	}else if(callTime.indexOf("秒") != -1 && callTime.indexOf("分") != -1){
					// 		this.minute = callTime.match(/分(\S*)秒/)[1];
					// 	}else if(callTime.indexOf("秒") != -1 && callTime.indexOf("分") == -1){
					// 		this.second = callTime.match(/分(\S*)/)[1];
					// 	}
					// }

					$("#carNumberInput").val(result.data.carNumber).change();
					var str=$("<span class='select2-selection__rendered'>"+result.data.carNumber+"</span>");
					$('#carNumberSelect2').val('');
					$("#select2-carNumberSelect2-container").empty();
					$("#select2-carNumberSelect2-container").attr("title",result.data.carNumber);
					$("#select2-carNumberSelect2-container").prepend(str);

					//显示图片
					this.page.complainPath = result.data.complainPath && result.data.complainPath.split(",");
					this.page.conversationPath = result.data.conversationPath && result.data.conversationPath.split(",");
					for(var i=0;i< this.page.complainPath.length;i++){
						this.imageInfo.imageList.push(this.page.complainPath[i]);
						
						let localImg;
						// if(this.page.complainPath[i][0] == '/'){
						// 	localImg = config.BaseURL + this.page.complainPath[i].substr(1);
						// }else{
						// 	localImg = config.BaseURL + this.page.complainPath[i];
						// }
						if(this.page.complainPath[i].indexOf('http') == -1){
							if(this.page.complainPath[i][0] == '/'){
								localImg = config.BaseURL + this.page.complainPath[i].substr(1);
							}else{
								localImg = config.BaseURL + this.page.complainPath[i];
							}
						}else{
							localImg = this.page.complainPath[i];
						}
						this.imageInfo.localImg.push(localImg);
						
					}

					for(var i=0;i< this.page.conversationPath.length;i++){
						this.imageCar.imageList.push(this.page.conversationPath[i]);
						
						let localImg;
						// if(this.page.conversationPath[i][0] == '/'){
						// 	localImg = config.BaseURL +this.page.conversationPath[i].substr(1);
						// }else{
						// 	localImg = config.BaseURL + this.page.conversationPath[i];
						// }
						if(this.page.conversationPath[i].indexOf('http') == -1){
							if(this.page.conversationPath[i][0] == '/'){
								localImg = config.BaseURL + this.page.conversationPath[i].substr(1);
							}else{
								localImg = config.BaseURL + this.page.conversationPath[i];
							}
						}else{
							localImg = this.page.conversationPath[i];
						}
						this.imageCar.localImg.push(localImg);
						
					}

					if(this.page.isNotice == "1"){
						this.isShared = false;
					}else{
						this.isShared = true;
					}
					if(this.page.isFix == "1"){
						this.repair = false;
					}else{
						this.repair = true;
					}
				}
			})
		}
	}
	//擦除车牌号码所选值
	del_carNumber() {
		this.page.deviceId = '';
		this.page.carNumber = '';
		this.page.companyName = '';
		this.page.companyId = '';
		$("#carNumberInput").val('').change();
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title", "");
		$("#select2-carNumberSelect2-container").prepend(str);
	}
	// select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
    }
    //是否是否通知司机
  	isSharedChange(val){
        this.page.isNotice = val;
        if(val == "1"){
            this.isShared = false
        }else{
            this.isShared = true
        }
    }
    //是否是否维修
    isRepairChange(val){
        this.page.isFix = val;
        if(val == "1"){
			this.repair = false
			// $("#appointRepairedTime").val('');
			// this.page.appointRepairedTime = '';
			// this.page.noRepairedReason = '';
        }else{
			this.repair = true
			// $("#fixTime").val('');
			// this.page.fixTime = '';
        }
    }
    //上传多张
	multifileChange(index,files: FileList){
		console.log("1111111111111")
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}

		var that = this;
		let multfileList = files;
		
        var reqdata = new FormData();
        if(index == 1){
            reqdata.append('describe',that.imageInfo.describe);
        }else{
            reqdata.append('describe',that.imageCar.describe);
        }
		
		reqdata.append('businessType', '3');
		// reqdata.append('type', '1');  //type 1获取相对路径  2获取绝对路径
		reqdata.append('deviceId',this.page.deviceId);
		reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径

		for(var i=0;i<multfileList.length;i++){
			this.fileList = multfileList[i];
			const isJPG = this.fileList.type === 'image/jpeg'|| this.fileList.type === 'image/jpg'|| this.fileList.type === 'image/png';
			if (!isJPG) {
			this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
			return;
			}

			reqdata.append('files',multfileList[i]);
			
		}
		

		that.jsonApiService.form_http("fileUpload/upload.html",reqdata).subscribe(data=> {
			// that.jsonApiService.message(data.message);
			if(data.success){
				for(var i=0;i< data.data.length;i++){
                    if(index == 1){
                        that.imageInfo.imageList.push(data.data[i]);
                    }else{
                        that.imageCar.imageList.push(data.data[i]);
                    }

					
					let localImg;
					// if(data.data[i][0] == '/'){
					// 	localImg = config.BaseURL + data.data[i].substr(1);
					// }else{
					// 	localImg = config.BaseURL + data.data[i];
					// }
					if(data.data[i].indexOf('http') == -1){
						if(data.data[i][0] == '/'){
							localImg = config.BaseURL + data.data[i].substr(1);
						}else{
							localImg = config.BaseURL + data.data[i];
						}
					}else{
						localImg = data.data[i];
					}
                    
                    if(index == 1){
                        that.imageInfo.localImg.push(localImg);
                    }else{
                        that.imageCar.localImg.push(localImg);
                    }
					
				}


				if(this.imageCar.imageList.length != 0){
					this.isShared = false;
					this.page.isNotice = "1";
				}
			}
		})
		

		for(let k=0;k<$(".up").length;k++){
			$(".up")[k].value=null;
		}
		
    }
    bigImgClick(type,modal,img){
		// modal.show();
		this.bigImg = img;
		if(this.isViewer && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showImg(type);
					})
				})
			})
		}else{
			this.showImg(type);
		}
    }
    showImg(type){
		var that = this;
		var imgList
		if(type == '1'){
			imgList = $(".imgFileList")[0];
		}else{
			imgList = $(".imgCarList")[0];
		}
		this.viewer = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
			},
		});
		that.isViewer = true
	}
    //删除
	deleteImg(index,i){
        if(index == 1){
            this.imageInfo.imageList.splice(i,1);
            this.imageInfo.localImg.splice(i,1);
        }else{
            this.imageCar.imageList.splice(i,1);
            this.imageCar.localImg.splice(i,1);
        }
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}

		if(this.imageCar.imageList.length != 0 || this.page.callDuration > 0){
			this.isShared = false;
			this.page.isNotice = "1";
		}else{
			this.isShared = true;
			this.page.isNotice = "0";
		}
    }
    //后台判断原因
  	reasonsChange(val){
        this.page.reasons = val;
    }
    //公司选中回调
	companySelected(data){
		this.page.companyId = data.companyId;
		this.page.companyName = data.companyName;
	}
	//通话时长
	callDuration(value){
		if(value != 0 || value != '' || this.imageCar.imageList.length != 0){
			this.isShared = false;
			this.page.isNotice = "1";
		}else{
			this.isShared = true;
			this.page.isNotice = "0";
		}
	}
}